package com.itheima.d6_tcp3;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class Client {
    public static void main(String[] args) throws IOException {
        //Socket
        //1、创建客户端对象，指定服务端的IP和端口
        Socket socket = new Socket("127.0.0.1", 8888);


        //线程专门用来收集服务端的信息
        InputStream netIn = socket.getInputStream();
        DataInputStream dataInput = new DataInputStream(netIn);
        new Thread(()->{
            while (true) {
                try {
                    String msg = dataInput.readUTF();
                    System.out.println("群聊数据：" + msg);
                } catch (IOException e) {
//                    e.printStackTrace();
                }
            }
        }).start();


        //2、获取输出流，封装为DataOutputStream
        Scanner sc = new Scanner(System.in);

        while (true) {
            System.out.println("请输入要发送的数据：");
            String msg = sc.nextLine();

            OutputStream netOut = socket.getOutputStream();
            DataOutputStream dataOut = new DataOutputStream(netOut);
            dataOut.writeUTF(msg);

            //如果用户输入的是886，则结束
            if (msg.equals("886")) {
                break;
            }
        }

        //3、释放资源
        socket.close();
    }
}
